/*
 * @Descripttion: 
 * @Author: MajorMayer
 * @Date: 2021-06-07 09:57:25
 * @LastEditors: MajorMayer
 * @LastEditTime: 2021-07-07 00:21:20
 */
import axios from 'axios'
import qs from 'qs'

import isThrottleApis from './throttleApis'

const instance = axios.create({
    timeout: 15000,
    timeoutErrorMessage: '服务连接超时,请重试'
})


let fromToken
let pending = []
let cancelToken = axios.CancelToken
let removePending = ({ url, method }) => {
    for (let p in pending)
        if (pending[p].u === url + '&' + method) {
            //取消请求
            pending[p].f();
            pending.splice(p, 1);
        }
}

export function get(url, params, token) {
    fromToken = token
    return instance.get(url, { params });
}

export function postByJson(url, params, token) {
    fromToken = token
    return instance.post(url, params);
}

export function postByFormData(url, params, token) {
    fromToken = token
    return instance.post(url, qs.stringify(params), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
}

export function postByQs(url, params, token) {
    fromToken = token
    return instance.post(url, {}, { params });
}

export function post(url, params, token) {
    fromToken = token
    return instance.post(url, JSON.stringify(params));
}

// 请求拦截器
instance.interceptors.request.use(
    config => {
        config.url = config.url

        if (fromToken) config.headers.token = fromToken
        else if (global.token) config.headers.token = global.token
        else config.headers.token = ''

        if (isThrottleApis(config.url)) {
            removePending(config);
            config.cancelToken = new cancelToken((c) => void pending.push({ u: config.url + '&' + config.method, f: c }));
        }

        return config;
    },
    error => {
        if (axios.isCancel(error))
            return Promise.reject(Error('isCancel'))

        console.log(error, 'request故障')

        if (error.response && error.response.status) {
            switch (error.response.status) {
                default: return Promise.reject(error)
            }
        }
        return Promise.reject(error || Error('网络故障'));
    }
)

// 响应拦截器
instance.interceptors.response.use(
    response => {
        removePending(response.config);

        var data = response.data;
        if (response.status == 200) {
            return Promise.resolve(data);
        }
        else return Promise.reject(Error(`${data.code} : ${data.msg}`));
    },
    error => {
        if (axios.isCancel(error))
            return Promise.reject(Error('isCancel'))

        console.log(error, 'response故障')

        if (error.response && error.response.status) {
            switch (error.response.status) {
                default: return Promise.reject(error || Error('网络故障'))
            }
        }
        return Promise.reject(error || Error('网络故障'));
    }
)